package com.meiborte.dao.impl;

import com.meiborte.dao.BookDao;
import com.meiborte.entity.Book;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class BookDaoimpl2 implements BookDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Book> findAll() {
        //lambda表达式
        String sql = "select * from books";

        List<Book> books = jdbcTemplate.query(sql, (resultSet, rowNum) -> {
            Book book = new Book().setId(resultSet.getInt("id"))
                    .setTitle(resultSet.getString("title"))
                    .setPrice(resultSet.getDouble("price"))
                    .setQuantity(resultSet.getInt("quantity"));
            return book;
        });
        return books;
    }

    @Override
    public int addBook(Book book) {
        String sql = "insert into books(title,price,quantity) values (?,?,?)";
        return jdbcTemplate.update(sql, book.getTitle(), book.getPrice(), book.getQuantity());
    }
    @Override
    public int updateBook(Book book) {
        String sql = "UPDATE books SET title = ?, price = ?, quantity = ? WHERE id = ?";
        return jdbcTemplate.update(sql, book.getTitle(), book.getPrice(), book.getQuantity(), book.getId());
    }
    @Override
    public int deleteBook(int id) {
        String sql = "delete from books where id=?";
        return jdbcTemplate.update(sql, id);
    }

}
